﻿using System;
using System.Collections.Specialized;
using System.Configuration;

namespace TSites.Service.Common.Utils
{
	public class AppConfig
	{
		private readonly static NameValueCollection _appConfig = ConfigurationManager.AppSettings;

		public static string GetString(string key, string defaultValue)
		{
			string value = _appConfig[key];
			if (string.IsNullOrWhiteSpace(value))
			{
				value = defaultValue;
			}

			return value;
		}

		public static int GetInt(string key, int defaultValue)
		{
			string valueString = GetString(key, string.Empty);
			int valueInt;
			if (!int.TryParse(valueString, out valueInt))
			{
				valueInt = defaultValue;
			}

			return valueInt;
		}

		public static string GetCustomString(string region, string key)
		{
			NameValueCollection collection = (NameValueCollection)ConfigurationManager.GetSection(region);
			if (collection != null)
			{
				return collection[key];
			}

			return string.Empty;
		}

		public static int GetCustomInt(string region, string key)
		{
			int value;
			if (!int.TryParse(GetCustomString(region, key), out value))
			{
				value = 0;
			}

			return value;
		}

		public static void Save(string key, string value)
		{
			// Open App.Config of executable
			Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

			// Add an Application Setting.
			config.AppSettings.Settings.Remove(key);
			config.AppSettings.Settings.Add(key, value);

			// Save the changes in App.config file.
			config.Save(ConfigurationSaveMode.Modified);

			// Force a reload of a changed section.
			ConfigurationManager.RefreshSection("appSettings");
		}
	}
}
